//
//  openJiraAppDelegate.m
//  openJira
//
//  Created by Vincent Demay on 29/04/10.
//  Copyright Goojet 2010. All rights reserved.
//

#import "OpenJiraAppDelegate.h"
#import "OJConnector.h"
#import "UserData.h"
#import "OJCreateIssueViewController.h"
#import "OJFilterListController.h"
#import "OJSearchIssueListController.h"

#import "OJConnector.h"

@implementation OpenJiraAppDelegate

@synthesize window;


- (void)applicationDidFinishLaunching:(UIApplication *)application {
	
    [window makeKeyAndVisible];
	[self loadHMI];
}

- (void) loadHMI {
	if (![UserData hasUser]) {
		[self loadLoginHMI];
	} else {
		//try to login
		if ([[OJConnector getDefault] loginWithUser:[UserData sharedData].login andPassword:[UserData sharedData].password]) {
			[self loadConnectedHMI];
		} else {
			[self loadLoginHMI];
		}
	}
}

- (void) loadLoginHMI {
	if (!loginController){
		loginController = [[OJLoginViewController alloc] initWithStyle:UITableViewStyleGrouped];
		loginController.delegate = self;
	}
	[window addSubview:loginController.view];
}

- (void) loadConnectedHMI {
	if (loginController && loginController.view.superview) {
		[loginController.view removeFromSuperview];
	}
	[[OJConnector getDefault] updatePriorities];
	[[OJConnector getDefault] updateStatuses];
	[[OJConnector getDefault] updateTypes];
	[[OJConnector getDefault] updateProjects];
	
	OJFilterListController *filterListController = [[OJFilterListController alloc] initWithStyle:UITableViewStyleGrouped];
	UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:filterListController];
	navigationController.navigationBar.tintColor = BG_COLOR;
	[filterListController release];
	
	OJCreateIssueViewController *createIssueController = [[OJCreateIssueViewController alloc] initWithStyle:UITableViewStyleGrouped];
	UINavigationController *navigationController2 = [[UINavigationController alloc] initWithRootViewController:createIssueController];
	navigationController2.navigationBar.tintColor = BG_COLOR;
	[createIssueController release];
	
	OJSearchIssueListController *searchIssueController = [[OJSearchIssueListController alloc] initWithStyle:UITableViewStylePlain];
	UINavigationController *navigationController3 = [[UINavigationController alloc] initWithRootViewController:searchIssueController];
	navigationController3.navigationBar.tintColor = BG_COLOR;
	[searchIssueController release];
	
	tabBarController = [[UITabBarController alloc] init];
	tabBarController.viewControllers = [NSArray arrayWithObjects: navigationController, navigationController2,navigationController3, nil];
	
	 [navigationController release];
	 [navigationController2 release];
	[navigationController3 release];
	 
	[window addSubview:tabBarController.view];
}


- (void)dealloc {
	[tabBarController release];
    [window release];
    [super dealloc];
}

#pragma mark OJLoginViewControllerDelegate

- (void) onLoggedIn:(OJLoginViewController*) ctrl {
	[self loadConnectedHMI];
}


@end
